﻿using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Web.Http;
using System.Diagnostics;
using Microsoft.WindowsAzure.Diagnostics;
using Microsoft.ApplicationServer.Caching;
using Newtonsoft.Json;

namespace CNI.NRT.WebAPI
{
    public class TemperatureController : ApiController
    {
        public HttpResponseMessage Get()
        {
            return new HttpResponseMessage()
            {
                Content = new StringContent("Hello from OWIN!")
            };
        }

        public HttpResponseMessage Get(int id)
        {
            string msg = String.Format("Hello from OWIN (id = {0})", id);
            return new HttpResponseMessage()
            {
                Content = new StringContent(msg)
            };
        }

        public HttpResponseMessage Post([FromBody]TemperatureModel t)
        {
            // record new state
            UpdateCache(t);

            // log the transaction
            string json = JsonConvert.SerializeObject(t);
            Logger.LogTemperatureData(json);

            return new HttpResponseMessage(System.Net.HttpStatusCode.OK);
        }

        private void UpdateCache(TemperatureModel t)
        {
            if (WorkerRole.myCache == null)
            {
                Trace.TraceError("Cache object not instantiated correctly.");
                return;
            }

            if (t == null)
            {
                Trace.TraceError("TemperatureModel object not instantiated correctly.");
                return;
            }

            // get the cached values 
            CacheTemperature cachedValues;
            try
            {
                cachedValues = (CacheTemperature)WorkerRole.myCache.Get(t.SensorID.ToString(), "SENSORS");
            }
            catch (DataCacheException dce)
            {
                Trace.TraceError("DataCacheException occurred while getting cached values: {0}", dce.Message);
                return;
            }
            catch (Exception ex)
            {
                Trace.TraceError("Exception occurred while getting cached values: {0}", ex.Message);
                return;
            }


            try
            {
                // initialize cached values if not already in cache
                if (cachedValues == null)
                {
                    cachedValues = new CacheTemperature();

                    cachedValues.Temperature = t.Temperature;
                    cachedValues.Timestamp = t.Timestamp;
                
                    var tags = new List<DataCacheTag>();
                    tags.Add(new DataCacheTag(t.DeviceClass));

                    WorkerRole.myCache.Put(t.SensorID.ToString(), cachedValues, tags, "SENSORS");
                }
                else
                {
                    cachedValues.Temperature = t.Temperature;
                    cachedValues.Timestamp = t.Timestamp;

                    WorkerRole.myCache.Put(t.SensorID.ToString(), cachedValues, "SENSORS");
                }
            }
            catch (DataCacheException dce)
            {
                Trace.TraceError("DataCacheException occurred while putting cached values: {0}", dce.Message);
                return;
            }
            catch (Exception ex)
            {
                Trace.TraceError("Exception occurred while putting cached values: {0}", ex.Message);
                return;
            }
        }
    }
}